package com.webchat.rmi.config;

import feign.Response;
import feign.Util;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class FeignConfig {

//   @Bean
//   public Decoder feignDecoder() {
//       return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
//   }
//
//   private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
//       return () -> {
//           List<HttpMessageConverter<?>> converters = new ArrayList<>();
//           // 支持 JSON 解析
//           converters.add(new MappingJackson2HttpMessageConverter());
//           // 支持纯文本解析（text/event-stream）
//           converters.add(new StringHttpMessageConverter());
//           return new HttpMessageConverters(converters);
//       };
//   }

    @Bean
    public Decoder feignDecoder(WebClient.Builder webClientBuilder) {
        return (response, type) -> {
            if (type.getTypeName().contains("Flux<String>")) {
                // 如果是 Flux<String>，使用 WebClient 解析 SSE 流
                return parseSseStream(response, webClientBuilder);
            } else {
                // 其他情况使用默认解析
                return new SpringDecoder(new ObjectFactory<>() {
                    @Override
                    public HttpMessageConverters getObject() {
                        return new HttpMessageConverters(
                                new MappingJackson2HttpMessageConverter(),
                                new StringHttpMessageConverter()
                        );
                    }
                }).decode(response, type);
            }
        };
    }

    private Flux<String> parseSseStream(Response response, WebClient.Builder webClientBuilder) {
        try {
            // 获取响应数据
            byte[] body = Util.toByteArray(response.body().asInputStream());
            String responseBody = new String(body);

            // 使用 WebClient 解析 SSE 流
            return webClientBuilder.build()
                    .post()
                    .uri("") // 这里可以模拟请求，或者直接解析 body
                    .contentType(MediaType.TEXT_EVENT_STREAM)
                    .bodyValue(responseBody)
                    .retrieve()
                    .bodyToFlux(String.class);
        } catch (IOException e) {
            return Flux.error(e);
        }
    }
}